package de.grosjohann.android.feuerwehr.webservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.telephony.TelephonyManager;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;

public class C2DMWsFacade
  extends AbstractWsFacade {

  public static int register(Context ctx, String registrationID) throws ClientProtocolException, IOException,
    HttpException {
    final String wsUri = "/c2dm/register";
    final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);

    C2DMWsClient client = createClient(ctx, baseUri + wsUri);

    List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();
    paramList.add(new BasicNameValuePair("registrationID", registrationID));
    paramList.add(new BasicNameValuePair("imei", tm.getDeviceId()));
    paramList.add(new BasicNameValuePair("os", "ANDROID"));

    NameValuePair[] paramArr = new BasicNameValuePair[paramList.size()];
    paramList.toArray(paramArr);

    return client.post(paramArr);
  }

  public static int unregister(Context ctx) throws ClientProtocolException, IOException, HttpException {
    final String wsUri = "/c2dm/unregister";
    final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);

    C2DMWsClient client = createClient(ctx, baseUri + wsUri);

    List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();
    paramList.add(new BasicNameValuePair("imei", tm.getDeviceId()));

    NameValuePair[] paramArr = new BasicNameValuePair[paramList.size()];
    paramList.toArray(paramArr);

    return client.post(paramArr);
  }

  private static C2DMWsClient createClient(Context ctx, String uri) throws ClientProtocolException, IOException {
    final int connectionTimeout =
        PrefsUtil.getInt(ctx, R.string.prefKeyConnectionTimeout, R.string.prefDefaultConnectionTimeout);
    final int socketTimeout = PrefsUtil.getInt(ctx, R.string.prefKeySocketTimeout, R.string.prefDefaultSocketTimeout);

    return new C2DMWsClient(uri, connectionTimeout, socketTimeout);
  }
}
